import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider, WeaTop, WeaTab, WeaLeftRightLayout, WeaLeftTree, WeaFormItem, WeaSearchGroup, WeaRightMenu, WeaErrorPage, WeaAlertPage } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { Button, Form } from 'antd';
import HighSeasDispenseDialog from '../dialog/HighSeasDispenseDialog';
import HighSeasLogDialog from '../dialog/HighSeasLogDialog';

@inject('highSeasApproveListStore')
@observer
class HighSeasApproveList extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { highSeasApproveListStore } = this.props;
    highSeasApproveListStore.initDatas();
  }

  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { highSeasApproveListStore } = nextProps;
      highSeasApproveListStore.initDatas();
    }
  }

  render() {
    const { highSeasApproveListStore } = this.props;
    const { counts, treeData, countsType, showLeft, tableStore, loading, showSearchAd, searchConditionForm, rightMenu, logDialogVisible, logType, searchBaseParams, topKey, hasApproveRight, verified } = highSeasApproveListStore;
    if (verified && !hasApproveRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ivn4z8`} >
        <div style={{ color: '#000' }}>
          {getLabel(2012, '对不起，您暂时没有权限！')}
        </div>
      </WeaAlertPage>
      );
    }

    const topTab = [
      {
        color: '#fea468',
        groupid: 'flowRes',
        showcount: true,
        title: getLabel(2242, '待审批'),
        viewcondition: 0,
      },
      {
        color: '#ff3232',
        groupid: 'flowNew',
        showcount: true,
        title: getLabel(387217, '待分配'),
        viewcondition: 1,
      }];
    const topTabCount = {
      flowRes: '2',
      flowNew: '3',
    };
    if (verified && hasApproveRight) {
      return (
        <div>
          <WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@v0fuu0`}
            datas={this.getRightMenus()}
            onClick={this.onRightMenuClick.bind(this)}
            collectParams={{
              favname: getLabel(16406, '客户审批'),
              favouritetype: 4,
              importantlevel: 1,
              objid: -1,
            }}
          >
            <WeaTop
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@xkacpt`}
              title={getLabel(16406, '客户审批')}
              icon={<i className="icon-coms-crm" />}
              iconBgcolor="#96358a"
              buttons={this.getButtons(this.props.ecId || '')}
              loading={loading}
              buttonSpace={10}
              dropMenuDatas={this.getRightMenus()}
            >
              <WeaLeftRightLayout
                ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@1egv6i`}
                leftWidth={240}
                leftCom={
                  <div style={{ height: '100%' }}>
                    <WeaLeftTree
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@2xcuem`}
                      searchLabel={getLabel(387161, '全部公海')}
                      datas={toJS(treeData)}
                      countsType={toJS(countsType)}
                      counts={toJS(counts)}
                      onSelect={((ids, nodeids, nodes, event) => {
                        highSeasApproveListStore.resetParams();
                        highSeasApproveListStore.seasId = ids;
                        highSeasApproveListStore.doSearch();
                      })}
                    />

                  </div>}
                onCollapse={showLeft => highSeasApproveListStore.isShowLeft(showLeft)}
                showLeft={showLeft}
              >
                <WeaTab
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@e8s3tf`}
                  datas={topTab}
                  // counts={topTabCount}
                  // countParam="groupid" //数量
                  selectedKey={topKey}
                  onChange={this.changeTopTab.bind(this)}
                  keyParam="viewcondition" // 主键
                  searchType={['base', 'advanced']}
                  searchsBaseValue={(searchBaseParams && searchBaseParams.name) || ''}
                  onSearchChange={v => highSeasApproveListStore.setSearchKey(v)}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getAdButtons(highSeasApproveListStore, this.props.ecId || '')}
                  setShowSearchAd={bool => highSeasApproveListStore.setShowSearchAd(bool)}
                  hideSearchAd={() => highSeasApproveListStore.setShowSearchAd(false)}
                  searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@hougaa`} horizontal>{this.getSearchConditionForm(highSeasApproveListStore)}</Form>}
                  onSearch={highSeasApproveListStore.doSearch}
                /><WeaTable
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@dsjvkb`}
                  comsWeaTableStore={tableStore}
                  hasOrder
                  needScroll
                />
              </WeaLeftRightLayout>
            </WeaTop>
            <HighSeasDispenseDialog ecId={`${this && this.props && this.props.ecId || ''}_HighSeasDispenseDialog@y2fjco`} contentStore={highSeasApproveListStore} />
          </WeaRightMenu>
          {logDialogVisible && <HighSeasLogDialog ecId={`${this && this.props && this.props.ecId || ''}_HighSeasLogDialog@2hsbjv`} contentStore={highSeasApproveListStore} logType={highSeasApproveListStore.logType} />}
        </div>
      );
    }

    return <div />;
  }

  getRightMenus() {
    const { highSeasApproveListStore } = this.props;
    const { rightMenu, tableStore, buttonDisabled } = highSeasApproveListStore;
    const { selectedRowKeys } = tableStore;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    const btnArr = [];
    rightMenu && rightMenu.map((m) => {
      btnArr.push({
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        disabled: (buttonDisabled || (isDisabled && m.isControl == '1')),
      });
    });
    return btnArr;
  }

  getAdButtons(store, ecId) {
    const { doSearch, setShowSearchAd, clearAdFields } = store;
    return [
      (<Button ecId={`${ecId}_Button@7kpp5e@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${ecId}_Button@2jkon2@reset`} type="ghost" onClick={() => { clearAdFields(); }}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${ecId}_Button@bq7bff@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }

  getSearchConditionForm(store) {
    const { searchConditionComponents, searchConditionForm } = store;
    const groups = [];
    if (searchConditionComponents) {
      const { isFormInit } = searchConditionForm;
      const formParams = searchConditionForm.getFormParams();
      isFormInit && toJS(searchConditionComponents).map((c, i) => {
        const items = [];
        c.items.map((fields, index) => {
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@8mfx61@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bzimn6@${fields.domkey[0]}`} fieldConfig={fields} form={searchConditionForm} formParams={formParams} onChange={store.searchConditionFieldChange} onEnterSearch={this.onEnterSearch} />
            </WeaFormItem>),
            col: 2,
          });
        });
        groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wpjty6@${i}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
    }
    return groups;
  }

  onRightMenuClick(key) {
    const { highSeasApproveListStore } = this.props;
    const { rightMenu, tableStore } = highSeasApproveListStore;
    const { selectedRowKeys } = tableStore;
    rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
        	if (Number(key) == i) {
        const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
        if (m.type == 'BTN_AGREE') {
          highSeasApproveListStore.approveCustomer(toJS(selectedRowKeys), '1');
        } else if (m.type == 'BTN_DISAGREE') {
          highSeasApproveListStore.approveCustomer(toJS(selectedRowKeys), '0');
        } else if (m.type == 'BTN_LOG') {
          highSeasApproveListStore.showLog();
        } else if (m.type == 'BTN_DISPENSE_CUSTOMER') {
          highSeasApproveListStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`);
        }
      }
    });
  }


  getButtons(ecId) {
    const { highSeasApproveListStore } = this.props;
    const { tableStore, rightMenu, buttonDisabled } = highSeasApproveListStore;
    const { selectedRowKeys } = tableStore;
    const btnArr = [];
    const that = this;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
      m.isTop == '1' && btnArr.length < 4 && btnArr.push(
        <Button
          ecId={`${ecId}_Button@xll806@${m.type}`}
          type={'primary'}
          disabled={buttonDisabled || (isDisabled && m.isControl == '1')}
          onClick={() => {
            const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
            if (m.type == 'BTN_AGREE') {
              highSeasApproveListStore.approveCustomer(toJS(selectedRowKeys), '1');
            } else if (m.type == 'BTN_DISAGREE') {
              highSeasApproveListStore.approveCustomer(toJS(selectedRowKeys), '0');
            } else if (m.type == 'BTN_DISPENSE_CUSTOMER') {
              highSeasApproveListStore.showCustomerModal(true, `${toJS(selectedRowKeys)}`);
            }
          }}
        >
          {m.menuName}
        </Button>,
      );
    });
    return btnArr;
  }

  changeTopTab(theKey) {
    const key = Number(theKey);
    const { highSeasApproveListStore } = this.props;
    highSeasApproveListStore.changeTopTab(key);
    // highSeasApproveListStore.initDatas();
  }

  onEnterSearch=() => {
    const { highSeasApproveListStore } = this.props;
    highSeasApproveListStore.doSearch();
  }
}


export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ssjczt`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(HighSeasApproveList);
